package com.vpx.server.mapper.system;

import com.vpx.server.bean.entity.SysUser;
import com.vpx.server.bean.info.system.SysUserInfo;
import com.vpx.server.bean.order.system.SysUserPageOrder;
import com.vpx.server.framework.base.BaseMapper;
import com.vpx.server.framework.utils.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;

import java.util.List;

/**
 * @author liuks
 * @title: vpx
 * @module: 用户管理
 * @description: 用户管理Mapper
 * @date 2021/09/11 13:37
 */
public interface SysUserMapper extends BaseMapper<SysUser> {

    /**
     * 更具登录账号查询数据记录条数
     * @param loginAccount
     * @return
     */
    @Select("select count(0) from sys_user where login_account = #{loginAccount}")
    int querySysUserCountByLoginAccount(@Param("loginAccount") String loginAccount);

    /**
     * 更具id和登录账号查询数据记录条数
     * @param id
     * @param loginAccoun
     * @return
     */
    @Select("select count(0) from sys_user where id = #{id} and login_account = #{loginAccount}")
    int querySysUserCountByIdAndLoginAccount(@Param("id") Long id, @Param("loginAccount") String loginAccoun);

    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @Select("select u.* from sys_user u where u.id = #{id}")
    SysUserInfo selectUserById(@Param("id") Long id);

    /**
     * 分页查询用户信息
     * @param order
     * @return
     */
    @SelectProvider(type = SysUserMapper.SqlProvider.class, method = "pageQuery")
    List<SysUserInfo> pageQuery(@Param("order") SysUserPageOrder order);

    class SqlProvider{
        public String pageQuery(@Param("order") SysUserPageOrder order){
            //StringBuffer sb = new StringBuffer("select u.*,d.data_range from sys_user u inner join sys_user_data d on u.id = d.user_id");
            //不能inner join ,应为user和数据权限是一对多的关系
            StringBuffer sb = new StringBuffer("select u.* from sys_user u ");
            Boolean where = false;
            if (StringUtils.isNotBlank(order.getUserName())) {
                where = SqlUtils.appWhere(where, sb, "u.user_name like ('%'+#{order.userName}+'%')");
            }
            if (StringUtils.isNotBlank(order.getLoginAccount())) {
                where = SqlUtils.appWhere(where, sb, "u.login_account like ('%'+#{order.loginAccount}+'%')");
            }
            if (StringUtils.isNotBlank(order.getUserCode())) {
                where = SqlUtils.appWhere(where, sb, "u.user_code = #{order.userCode}");
            }
            if (StringUtils.isNotBlank(order.getMobilePhone())) {
                where = SqlUtils.appWhere(where, sb, "u.mobile_phone = #{order.mobilePhone}");
            }
            sb.append(" order by u.create_time desc");
            return sb.toString();
        }
    }
}
